//
//  database.m
//  iCodeMacRun
//
//  Created by Andrew Barry on 30/05/09.
//  Copyright 2009 Barry Computer Services. All rights reserved.
//

#import "database.h"
#import "jvmrun.h"

static JSBool dbSelect(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) {
	if (argc == 0)
		return JS_TRUE;
	NSString *sql = valToString(cx, argv[0]);
	*rval = [[jvmrun instance] dbSelect: [sql UTF8String] withArgs: argv + 1 withArgCount: argc - 1 ];
	return JS_TRUE;
}

static JSBool dbExecute(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) {
	if (argc == 0)
		return JS_TRUE;
	NSString *sql = valToString(cx, argv[0]);
	[[jvmrun instance] dbExecute: [sql UTF8String] withArgs: argv + 1 withArgCount: argc - 1 ];
	return JS_TRUE;
}

static JSBool dbConnect(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) {
	NSString *uid = @"";
	NSString *pwd = @"";
	
	if (argc > 0)
		uid = valToString(cx, argv[0]);
	if (argc > 1)
		pwd = valToString(cx, argv[1]);

	bool result = [[jvmrun instance] dbConnect: uid withPassword: pwd];
	*rval = BOOLEAN_TO_JSVAL(result);
	return JS_TRUE;
}

static JSBool dbClose(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) {
	[[jvmrun instance] dbClose];
	*rval = BOOLEAN_TO_JSVAL(1);
	return JS_TRUE;
}

JSObject *gSQLFileObject;

void registerDatabase(JSContext *cx, JSObject *global) {
	JS_AddRoot(cx, &gSQLFileObject);
	gSQLFileObject = JS_NewObject(cx, nil, nil, nil);
	
	JS_DefineProperty(cx, global, "SQL", OBJECT_TO_JSVAL(gSQLFileObject), NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT);
	JS_DefineFunction(cx, gSQLFileObject, "select", dbSelect, 1, 0);
	JS_DefineFunction(cx, gSQLFileObject, "execute", dbExecute, 1, 0);
	JS_DefineFunction(cx, gSQLFileObject, "connect", dbConnect, 2, 0);
	JS_DefineFunction(cx, gSQLFileObject, "close", dbClose, 0, 0);

}
